<template>
  <div class="personal-center">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>个人中心</span>
        </div>
      </template>

      <div class="user-info">
        <!-- 头像上传区域 -->
        <div class="avatar-upload">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :headers="{'jobSeekerToken': token}"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">点击上传头像</div>
        </div>

        <!-- 基本信息表单 -->
        <el-form
          ref="userFormRef"
          :model="userForm"
          :rules="userRules"
          label-width="100px"
          class="user-form"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email" />
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userForm.phone" />
          </el-form-item>

          <el-form-item label="用户类型">
            <el-tag :type="userTypeTag">
              {{ userTypeMap[userForm.userType] }}
            </el-tag>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitUserForm">保存修改</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 修改密码区域 -->
      <el-divider />
      <div class="password-change">
        <h3>修改密码</h3>
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
          class="password-form"
        >
          <el-form-item label="原密码" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              show-password
            />
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitPasswordForm">
              修改密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getInfoApi, updateInfoApi, updatePwdApi } from '../../api/jobSeeker'
import router from '../../router'

onMounted(() => {
  loadUserInfo()
  getToken()
})
const token = ref('')
//获取token
const getToken = () => {
  const user = JSON.parse(localStorage.getItem('jobseekerInfo'))
  if(user && user.token){
    token.value = user.token
  }else{
    token.value = ''
  }
}
// 用户类型映射
const userTypeMap = {
  1: '普通用户',
  2: '企业用户',
  3: '管理员'
}

// 用户类型标签样式
const userTypeTag = computed(() => {
  switch (userForm.user_type) {
    case 1: return ''
    case 2: return 'success'
    case 3: return 'danger'
    default: return 'info'
  }
})

// 用户表单数据
const userForm = ref({
  id: null,
  username: '',
  email: '',
  phone: '',
  avatar: '',
  userType: 1
})

// 用户表单验证规则
const userRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2到20个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
  ]
})

// 密码表单数据
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单验证规则
const passwordRules = reactive({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

const userFormRef = ref(null)
const passwordFormRef = ref(null)

// 加载用户信息
const loadUserInfo = async () => {
  const res = await getInfoApi()
  if(res.code){
    userForm.value = res.data
  }else{
    ElMessage.error('获取用户信息失败')
  }
}

// 提交用户信息修改
const submitUserForm = async () => {
  try {
    await userFormRef.value.validate()
    // 这里调用API更新用户信息
    console.log('更新用户信息：', userForm.value)
    const result = await updateInfoApi(userForm.value)
    // await updateUserInfo(userForm)
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    if (error !== 'validate') {
      ElMessage.error('更新用户信息失败')
    }
  }
}

// 提交密码修改
const submitPasswordForm = async () => {
  try {
    await passwordFormRef.value.validate()
    // 这里调用API修改密码
    const result = await updatePwdApi(passwordForm.value.oldPassword, passwordForm.value.newPassword)
    if(result.code){
      ElMessage.success('密码修改成功')
      passwordFormRef.value.resetFields()
      router.push('/')
    }else{
      ElMessage.error(result.msg)
    }
  } catch (error) {
    if (error !== 'validate') {
      ElMessage.error('表单验证不通过')
    }
  }
}

// 头像上传处理
const handleAvatarSuccess = (response) => {
  // 处理头像上传成功逻辑
  userForm.value.avatar = response.data
}

const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}
</script>

<style scoped>
.personal-center {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.user-info {
  display: flex;
  gap: 40px;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 180px;
}

.avatar-uploader {
  width: 120px;
  height: 120px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.upload-tip {
  margin-top: 10px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.user-form {
  flex: 1;
}

.password-change {
  margin-top: 20px;
}

.password-change h3 {
  margin-bottom: 20px;
}

.password-form {
  max-width: 500px;
}

.el-divider {
  margin: 30px 0;
}
</style>